﻿/**
 * Copyright (C) 2011 original author and authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NGuice.Inject.Spi;
using System.Collections.ObjectModel;
using NGuice.Inject.Internal;
using NGuice.Inject.Internal.Util;

namespace NGuice.Inject
{
    /// <summary>
    /// 当程序错误时发生，例如丢失元特性、错误的绑定或不支持的scope。客户端需要捕获此异常并记录日志，停止运行
    /// </summary>
    public sealed class ConfigurationException : NGuiceException
    {
        private readonly ICollection<Message> messages;

        private object partialValue = null;

        /** Creates a ConfigurationException containing {@code messages}. */
        public ConfigurationException(IEnumerable<Message> messages)
        {
            this.messages = new ReadOnlyCollection<Message>(messages.ToList());
            InitCause(Errors.GetOnlyCause(this.messages));
        }

        /** Returns a copy of this configuration exception with the specified partial value. */
        public ConfigurationException WithPartialValue(object partialValue)
        {
            Preconditions.CheckState(this.partialValue == null, "Can't clobber existing partial value {0} with {1}", this.partialValue, partialValue);
            ConfigurationException result = new ConfigurationException(messages);
            result.partialValue = partialValue;
            return result;
        }

        public ICollection<Message> ErrorMessages
        {
            get
            {
                return messages;
            }
        }

        public E GetPartialValue<E>()
        {
            return (E)partialValue;
        }

        public object GetPartialValue()
        {
            return partialValue;
        }

        public override string Message
        {
            get
            {
                return Errors.Format("NGuice configuration errors", messages);
            }
        }
    }
}
